package com.blank.shop.seata.account;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.blank.shop.seata.ShopAlibabaSeataApplication;
import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <br/>Date 2021/8/30
 * <br/>Time 16:09:58
 *
 * @author _blank
 */
@Profile({ShopAlibabaSeataApplication.PROFILE_ACCOUNT})
@RestController
public class AccountController {

    public static final String UPDATE_SQL = "UPDATE t_account SET residue=residue-?,used=used+? WHERE user_id=?";

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 扣减余额
     *
     * @param userId 用户id
     * @param money  金额
     * @return org.springframework.http.ResponseEntity
     */
    @PostMapping(path = "account-decrease")
    ResponseEntity<String> decrease(Long userId, BigDecimal money) {
        try {
            DynamicDataSourceContextHolder.push(ShopAlibabaSeataApplication.DS_ACCOUNT);
            final int affectedRows = this.jdbcTemplate.update(UPDATE_SQL
                    , money
                    , money
                    , userId
            );
            return ResponseEntity.ok("account-decrease-ok-" + affectedRows);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }

}
